import logging
from logging.handlers import TimedRotatingFileHandler
# import CoTec.core.config.global_var
from CoTec.core.SMTP.smtp_go import SMTPServer

import os

class LogGo:

    logger_debug = logging.getLogger('log_debug')
    logger_info = logging.getLogger('log_info')
    logger_warning = logging.getLogger('log_warning')
    logger_error = logging.getLogger('log_error')
    logger_criticals = logging.getLogger('log_critical')

    logger_console = logging.getLogger('log_console')

    config = None

    logs = [('log_debug', logger_debug, logging.DEBUG), ('log_info', logger_info, logging.INFO), ('log_warning', logger_warning, logging.WARNING), ('log_error', logger_error, logging.ERROR), ('log_critical', logger_criticals, logging.CRITICAL)]
    logs_path = "logs/"

    formatter = logging.Formatter(fmt='[%(asctime)s] %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')

    @staticmethod
    def init(conf):
        LogGo.config = conf

        for tag, logger, degree in LogGo.logs:
            LOG_FILE = conf.root_path + LogGo.logs_path + tag
            hdlr = TimedRotatingFileHandler(LOG_FILE, when='D', interval=1, backupCount=40)
            hdlr.setFormatter(LogGo.formatter)
            logger.addHandler(hdlr)
            logger.setLevel(degree)

        # 定义一个StreamHandler，将INFO级别或更高的日志信息打印到标准错误，并将其添加到当前的日志处理对象#
        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        console.setFormatter(LogGo.formatter)

        LogGo.logger_console.addHandler(console)

    @staticmethod
    def debug(msg):
        LogGo.logger_debug.debug(msg)
        LogGo.logger_console.debug(msg)

    @staticmethod
    def info(msg):
        LogGo.logger_info.info(msg)
        LogGo.logger_console.info(msg)

    @staticmethod
    def warning(msg):
        LogGo.logger_warning.warning(msg)
        LogGo.logger_console.warning(msg)

    @staticmethod
    def error(msg):
        LogGo.logger_error.error(msg)
        LogGo.logger_console.error(msg)

        if LogGo.config.error_mail:
            SMTPServer.report('System error: ' + '\r\n' + msg)

    @staticmethod
    def critical(msg):
        LogGo.logger_criticals.critical(msg)
        LogGo.logger_console.critical(msg)

        if LogGo.config.error_mail:
            SMTPServer.report('System down! Fatal error: ' + '\r\n' + msg)

    @staticmethod
    def fatal(msg):
        LogGo.critical(msg)
